class BlogController < ApplicationController
  def index
    @blog_posts = BlogPost.paginate(:page => params[:page], :conditions => {:is_published => true}, :order => 'created_at DESC')
    @tags       = Tag.all(:limit => 7, :order => "count desc")
    @page_title = "This site's Blog"
  end

  def show
    requested_date  = Time.local(params[:year], params[:month], params[:day])
    @blog_posts     = [BlogPost.find(:first, :conditions => ["date_format(published_at,'%Y%m%d') = ? and stub_name = ? and is_published = ?", requested_date.strftime("%Y%m%d"), params[:stub], true])]
    @tags           = @blog_posts.first.tags
    @page_title     = @blog_posts.first.title
    
    if @blog_posts.blank?
      render_404
    else
      render :action => :index
    end
  end

  def date_archive
    requested_date  = Time.local(params[:year], params[:month],1)
    @blog_posts     = BlogPost.paginate(:conditions => ["is_published = ? and published_at between ? and ?", true, requested_date.beginning_of_month.to_s(:db), requested_date.end_of_month.to_s(:db)], :page => params[:page], :order => 'created_at DESC')
    @tags           = Tag.all(:limit => 7, :order => "count desc")
    @page_title     = "This site's blog from #{requested_date.strftime('%B')} #{requested_date.strftime('%Y')}"
    
    if @blog_posts.size == 0
      render_404
    else
      render :action => :index
    end
  end
  
  def category
    @tag          = Tag.find :first, :conditions => {:stub_name => params[:tag]}
    @blog_posts   = @tag.blog_posts.paginate(:page => params[:page], :conditions => {:is_published => true}, :order => 'created_at DESC')
    @tags         = [@tag]
    @page_title     = "This site's articles about #{@tag.name}"
    
    if @blog_posts.size == 0
      render_404
    else
      render :action => :index
    end
    
  end

end
